<template>
  <div>
    <!-- 企业类型平均薪酬 -->
    <el-row class="search-container"> </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
        <div class="regionLineDesc">
          <div class="cityTitle">{{ currentChartRegionName }}</div>
          <div
            class="regionLineDescItem"
            v-for="(item, index) in chartDescData"
            :key="index"
          >
            <div class="descTitle">{{ item.keyName }}平均薪酬约</div>
            <div class="descNum">
              <span class="rmb">￥</span>{{ item.salary }}/<span class="rmb"
                >月</span
              >
            </div>
          </div>
        </div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else
        ><el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button></el-empty
      >
    </div>
  </div>
</template>

<script>
import { positionSalaryHistogram, reportLackDataPosition } from '@/api/salary';
// import IndustryCheckbox from "@/components/IndustryCheckbox/index";

export default {
  name: 'companyAverageSalaryChart',
  components: {
    // IndustryCheckbox,
  },
  data() {
    return {
      resData: [],
      chartData: {},
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      selectBetweenTime: [],
      pickerMinDate: '',
      firstDayofLastMonth: '',
      pickerOptions: {
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 6 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        }
      },
      average: '',
      selectedRegionList: [],
      regionLineDescAvg: '',

      isSetDeaultTime: false,
      currentChartRegionName: '',
      chartDescData: []
    };
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;
  },
  mounted() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let newYear = 0;
    let newMonth = 0;
    let newDateArr = [];
    for (let i = 0; i < 7; i++) {
      //这里是获取前六个月,所以循环6次,根据需要修改
      if (month - i < 1) {
        //这里的判断是如果当前月份往前推到了去年  需要做的处理
        newYear = year - 1;
        newMonth =
          month - i + 12 >= 10 ? month - i + 12 : '0' + (month - i + 12);
        newDateArr.push(newYear + '-' + newMonth + '-' + '01'); //这里拼接格式化,在时间中间加了个-,根据实际需求来
      } else {
        newMonth = month - i >= 10 ? month - i : '0' + (month - i); //这里是对月份小于10做加前面加0处理
        newDateArr.push(year + '-' + newMonth + '-' + '01');
      }
    }
    //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
    const end = newDateArr[1];
    const start = newDateArr[6];
    this.selectBetweenTime = [start, end];
    this.fetchData();
  },
  computed: {
    isLabelShow() {
      return this.$store.state.chart.isLabelShow;
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      const params = {
        ylPositionId: this.$route.query.id,
        keyType: 2,
        keyId: this.selectedRegionList[0]
      };
      if (this.selectBetweenTime != null && this.selectBetweenTime != '') {
        params.beginTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
      }
      //新接口08-16
      positionSalaryHistogram(params)
        .then((response) => {
          if (response.code == 200) {
            this.resData = response.data;
            this.chartDescData = response.data;
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
            this.$emit('onChartDataChange', this.resData);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      let dataArr = {
        city: [],
        salary: []
      };
      data.forEach((element) => {
        dataArr.city.push(element.keyName);
        dataArr.salary.push(element.salary);
      });

      return dataArr;
    },
    onIndustryChange(val) {
      this.currentChartRegionName = val[0].split('-')[1];
      this.selectedRegionList = [];
      val.forEach((item) => {
        this.selectedRegionList.push(item.split('-')[0]);
      });
      this.fetchData();
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let city = this.chartData.city,
        salary = this.chartData.salary;
      let option = {
        xAxis: {
          type: 'category',
          data: city,
          name: '(规模 人)',
          interval: 0,
          axisLabel: {
            color: '#8193B2',
            interval: function () {
              return 1; // 显示所有标签
            },
            formatter(val) {
              // //console.log("val", val);
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split('');
                const index = array.indexOf('-');
                //在下标2处删除0个，加上回车
                array.splice(index + 1, 0, ' ');
                array.splice(index, 0, '\n\n');
                return array.join('');
              } else {
                return val;
              }
            }
          },

          axisLine: {
            lineStyle: {
              color: '#E4EDF8'
            }
          },
          nameTextStyle: {
            lineHeight: 30, //标题行高
            color: '#8193B2',
            verticalAlign: 'top', //标题位置
            padding: [-2, 0, 0, 0] // 上右下左与原位置距离
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#000000'
            }
          },
          backgroundColor: '#0DC083',
          borderColor: '#0DC083',
          textStyle: {
            color: '#fff'
          },
          formatter: (params) => {
            const content = params[0];
            return `月收入平均值 ¥${content.value}`;
          }
          // position: ["50%", 0],
        },
        grid: {
          right: '70',
          bottom: '50',
          top: '50',
          left: '50'
        },
        yAxis: {
          type: 'value',
          name: '(薪酬 元)',
          axisLabel: {
            color: '#8193B2',
            fontSize: '12px'
          },
          axisLine: {
            lineStyle: {
              color: '#E4EDF8'
            }
          },
          nameTextStyle: {
            padding: [0, 45, 10, 0], // 上右下左与原位置距离
            color: '#8193B2'
          }
        },
        series: [
          {
            data: salary,
            type: 'bar',
            showBackground: false,
            barWidth: '18px',
            label: {
              show: this.isLabelShow,
              position: 'top'
            },
            itemStyle: {
              normal: {
                color: this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    //只要修改前四个参数就ok
                    offset: 0,
                    color: '#91E2B6'
                  }, //柱图渐变色
                  {
                    offset: 1,
                    color: '#A3DBFF'
                  }
                ]),
                borderRadius: [4, 4, 0, 0]
              }
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#1BD46E' // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#398AFF' // 100% 处的颜色
                    }
                  ],
                  global: false // 缺省为 false
                }
              }
            }
          }
        ]
      };
      this.myChart.on('mouseover', (params) => {
        this.$emit('update:hoverValue', params.value + '');
        this.$emit('update:hoverName', params.name);
      });
      option && this.myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      document.addEventListener('fullscreenchange', function () {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: 1
      });
      this.$emit('update:hoverValue', this.chartData.salary[1]);
      this.$emit('update:hoverName', this.chartData.city[1]);
    },
    onWorkYearChange(val) {
      this.fetchData();
    },
    handleDateChange(val) {
      if (this.isSetDeaultTime) {
        this.isSetDeaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      this.fetchData();
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = '';
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: '176',
        layerName: '企业类型平均薪酬',
        personId: localStorage.getItem('personId') || '',
        oaId: oaId
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success('已成功提交');
        } else {
          this.$message.error(res.status_desc);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  margin-top: 16px;
  color: #222;
  font-weight: bold;
  margin-bottom: 22px;
  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.chartMain {
  display: flex;
  // align-items: center;
  margin-left: 0px;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
  .h100 {
    flex: 0.65;
  }
  .regionLineDesc {
    /* // margin-left: 45px; */
    display: flex;
    flex: 0.35;
    flex-wrap: wrap;
    /* width: 400px; */
    justify-content: space-between;
    // align-content: center;
    margin: 10px 10px 10px 10px;
    .cityTitle {
      display: flex;
      width: 100%;
      margin: 10px auto;
      font-size: 18px;
      font-weight: bold;
      color: #222;
      align-items: center;
    }

    .regionLineDescItem {
      margin: 10px 0px;
      width: 48%;
    }
    .descTitle {
      color: #555;
      font-size: 15px;
    }
    .descNum {
      display: flex;
      align-items: baseline;
      color: #1b78ff;
      font-size: 24px;
      font-weight: bold;
      margin-top: 22px;
      font-family: D-DIN-PRO-500-Medium;
    }
    .rmb {
      font-size: 18px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  // margin-left: 45px;
  display: flex;
  flex: 0.3;
  flex-wrap: wrap;
  // width: 400px;
  justify-content: left;
  .regionLineDescItem {
    margin: 10px;
  }
}
.descTitle {
  color: #555;
  font-size: 15px;
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 24px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-500-Medium;
}
.rmb {
  font-size: 22px;
}
.h100 {
  width: 100%;
  // height: 16vw;
  min-width: 615px;
  min-height: 280px;
}

::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  line-height: 22px;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 内容超出容器部分隐藏 */
  text-overflow: ellipsis; /* 使用省略号表示被截断的内容 */
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
}
.search-container {
  display: flex;
  align-items: center;
  margin-left: 0px;
}
</style>
